import time

import requests , re

from utils.handle_ini import conf
from utils.handle_log import log
from utils.handle_attribute import HandleAttr

class SendRequests:
    def __init__(self):
        host = conf.get(section="URL",option="host")
        self.headers = {"Content-Type": "application/json","host":host}

    def __handle_url(self,uri):
        base_url = conf.get(section="URL",option="base_url")
        request_url = base_url + uri
        new_url = self.__handle_replace_url(request_url)
        return new_url

    #用于检测请求url中是否存在需要填充的参数，如果有则从公共类中提取对应属性进行填充
    def __handle_replace_url(self,url:str):
        re_str = "#(\w.+?)#"
        # re_str = bytes(re_str,'utf-8')
        key_list = re.findall(re_str,url)
        log.info(msg=f"正则匹配到的url中代替换字段列表:{key_list}")
        if len(key_list)>0:
            for key in key_list:
                if hasattr(HandleAttr,key):
                    url = url.replace(f"#{key}#",str(getattr(HandleAttr,key)))
                    log.info(msg=f"替换后的url:{url}")
                else:
                    log.info(msg="url中需要被替换的字段在HandleAttr中不存在，替换失败")
                return url
        else:
            log.info(msg="url中不存在需要替换的字段，无需进行替换处理")
            return url

    #将前置提取的token存入HandleAttr之后，设置到请求头中
    def __handle_token(self):
        if hasattr(HandleAttr,"token"):
            self.headers["Authorization"] = f'Bearer {str(getattr(HandleAttr,"token"))}'
            if hasattr(HandleAttr,"guid"):
                self.headers["guid"] = getattr(HandleAttr,"guid")
            else:
                log.info(msg="HandleAttr中不存在guid，请检查guid是否成功被提取和保存")
        else:
            log.info(msg="HandleAttr中不存在toekn，请检查token是否成功被提取和保存")

    def send_request(self,method,uri,data):
        """
        :param method: 请求方法
        :param uri: 请求地址
        :param data: 请求参数
        :return: 返回接口响应结果
        """
        try:
            log.info(msg='========开始发起请求========')
            log.info(msg='请求参数：\n{}'.format(data))
            new_method = method.upper()
            log.info(msg='请求方式:\n{}'.format(new_method))
            new_url = self.__handle_url(uri=uri)  # 请求地址拼接，参数替换
            log.info(msg='请求地址:\n{}'.format(new_url))
            self.__handle_token()  # 请求头处理

            if new_method == 'GET':
                response = requests.get(url=new_url,params=data,headers = self.headers)
                log.info(msg='GET请求返回:\n{}'.format(response.json()))
                return response.json()
            elif new_method == 'POST':
                response = requests.post(url=new_url, json=data, headers=self.headers)
                log.info(msg='POST请求返回:\n{}'.format(response.json()))
                return response.json()
            elif new_method == 'PATCH':
                response = requests.patch(url=new_url, json=data, headers=self.headers)
                log.info(msg='patch请求返回:\n{}'.format(response.json()))
                return response.json()
            else:
                log.info(msg='{}请求类型暂不支持,后续再增加'.format(method))
                raise AssertionError

            time.sleep(0.5)
        except Exception as e:
            log.error(msg='========请求发送结束，请求报错了========')
            log.exception(e)
            raise